package com.zzyl.nursing.service.impl;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import static com.zzyl.common.constant.CacheConstants.ALERT_TRIGGER_COUNT_PREFIX;

/**
 * 报警规则Service业务层处理
 *
 * @author anshibo
 * @date 2025-10-20
 */
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper,AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return save(alertRule)?1:0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return updateById(alertRule)?1:0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return removeById(id)?1:0;
    }



    @Override
    public void alertFilter() {
        //开始
        //查询所有规则
        List<AlertRule> list = this.list();
        if(CollUtil.isEmpty(list)){
            //规则为空结束
            return;
        }
        //规则不为空查询所有设备上报的最新的一条数据（redis）
        List<Object> values = redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).values();
        if(CollUtil.isEmpty(values)){
            //数据为空结束
            return;
        }
        //准备一个大的集合
        List<DeviceData> deviceDataList = new ArrayList<>();
        //数据非空，数据格式标准化处理,把数据放在大的集合中（遍历）
        for (Object value : values) {
            //对象转字符串再转目标对象的list
            List<DeviceData> list1 = JSONUtil.toList(value.toString(), DeviceData.class);
            //add添加单个对象，addAll添加list
            deviceDataList.addAll(list1);
        }
        //处理每一条数据
        for (DeviceData deviceData : deviceDataList) {
            //数据报警处理器
            alterFilter(deviceData);
        }
    }
    /**
     *
     * 数据报警处理器
     *
     */
    private void alterFilter(DeviceData deviceData) {
        //查询所有设备的数据,-1是全部设备
        LambdaQueryWrapper<AlertRule> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(AlertRule::getFunctionId,deviceData.getFunctionId());
        queryWrapper1.eq(AlertRule::getProductKey,deviceData.getProductKey());
        queryWrapper1.eq(AlertRule::getIotId,-1);
        queryWrapper1.eq(AlertRule::getStatus,1);
        List<AlertRule> list1 = this.list(queryWrapper1);
        //查询指定设备的数据
        LambdaQueryWrapper<AlertRule> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(AlertRule::getFunctionId,deviceData.getFunctionId());
        queryWrapper2.eq(AlertRule::getProductKey,deviceData.getProductKey());
        queryWrapper2.eq(AlertRule::getIotId,deviceData.getIotId());

        List<AlertRule> list2 = this.list(queryWrapper2);
        //合并两个集合
        Collection<AlertRule> alertRules = CollUtil.addAll(list1, list2);
        if(CollUtil.isEmpty(alertRules)){
            //数据为空结束
            return;
        }
        for (AlertRule alertRule : alertRules) {
            //对每条数据做校验
            deviceDataAlarmHander(alertRule,deviceData);
        }
    }
    /**
     *
     * 对每条数据做校验
     *
     */
    @Autowired
    private  ScriptEngine scriptEngine;
    private void deviceDataAlarmHander(AlertRule alertRule,DeviceData deviceData) {
        //获得报警生效时段
        String period = alertRule.getAlertEffectivePeriod();
        //根据~分割
        String[] split = period.split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        //数据生成时间
        LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();
        //判断时间
        if(alarmTime.isBefore(startTime)||alarmTime.isAfter(endTime)){
            return;
        }
        //连续触发次数，后面加数据是为了区分
        String alertCountKey = ALERT_TRIGGER_COUNT_PREFIX+deviceData.getIotId()+deviceData.getProductKey()+alertRule.getFunctionId()+ alertRule.getId();
        //报警规则沉默周期，后面加数据是为了区分
        String slientKey = CacheConstants.ALERT_SILENT_PREFIX+deviceData.getIotId()+ deviceData.getProductKey()+ alertRule.getFunctionId()+alertRule.getId();
        //定义表达式  设备的数据 > 规则的数据
        String expression = deviceData.getDataValue()+alertRule.getOperator()+alertRule.getValue();
        //判断是否达到阈值
        Boolean isReach = false;
        try {
            //执行表达式
            isReach = (Boolean) scriptEngine.eval(expression);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        if(!isReach){
            //到达阈值，删除redis里面的记录
            redisTemplate.delete(alertCountKey);
            return;
        }
        //获取沉默周期
        Boolean b = redisTemplate.hasKey(slientKey);
        //沉默周期内，结束
        if(b){
            return;
        }
        //获取连续触发次数
        Long alertCount = redisTemplate.boundValueOps(alertCountKey).increment();
        //判断是否达到持续周期
        if(alertCount>=alertRule.getDuration()){
            //可以报警了
            //删除redis里面的记录
            redisTemplate.delete(alertCountKey);
            //设置沉默周期
            redisTemplate.boundValueOps(slientKey).set("",alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
            //插入报警数据
            inserAlertData(alertRule,deviceData);
        }

    }
    /**
     *
     * 插入报警数据
     *
     */

    @Value("${alert.deviceMaintainerRole}")
    //行政
    private String deviceMaintainerRole;
    @Value("${alert.managerRole}")
    //管理员
    private String managerRole;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IAlertDataService alertDataService;
    private void inserAlertData(AlertRule alertRule, DeviceData deviceData) {


        // 查人
        // locationType '位置类型 0：随身设备 1：固定设备',
        // 判断上报的数据是否为老人的数据
        List<Long> userIds = List.of();
        if (deviceData.getLocationType().equals(0)) {
            // 随身的
            // 根据这个设备找到护理员
            userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
        }else{
            // 继续判断固定设备是在床位上还是在房间里
            // physicalLocationType：'物理位置类型 0楼层 1房间 2床位',
            if (deviceData.getPhysicalLocationType().equals(1)) {
                userIds = sysUserRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);

            }else if (deviceData.getPhysicalLocationType().equals(2)){
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        }
        //所有的报警数据都要经过超级管理员
        List<Long> adminIds = sysUserRoleMapper.selectUserIdByRoleName(managerRole);

        // 合并ids
        Collection<Long> userIdList = CollUtil.addAll(userIds, adminIds);
        // 去重
        userIdList = CollUtil.distinct(userIdList);


        List<AlertData> alertDataList = new ArrayList<>();
        for (Long userId : userIdList) {
            AlertData alertData = new AlertData();
            alertData.setIotId(deviceData.getIotId());
            alertData.setDeviceName(deviceData.getDeviceName());
            alertData.setProductKey(deviceData.getProductKey());
            alertData.setProductName(deviceData.getProductName());
            alertData.setFunctionId(deviceData.getFunctionId());
            alertData.setAccessLocation(deviceData.getAccessLocation());
            alertData.setLocationType(deviceData.getLocationType());
            alertData.setPhysicalLocationType(deviceData.getPhysicalLocationType());
            alertData.setDeviceDescription(deviceData.getDeviceDescription());

            alertData.setDataValue(deviceData.getDataValue());
            alertData.setAlertRuleId(alertRule.getId());
            // 报警原因，格式：功能名称+运算符+阈值+持续周期+聚合周期
            alertData.setAlertReason(deviceData.getFunctionId()+alertRule.getOperator()+alertRule.getValue()+alertRule.getDuration()+alertRule.getAlertSilentPeriod());

            alertData.setType(alertRule.getAlertDataType());
            alertData.setStatus(0); //状态，0：待处理，1：已处理
            alertData.setUserId(userId);

            alertDataList.add(alertData);
        }
        //批量插入报警数据
        alertDataService.saveBatch(alertDataList);
        // 发送websocket消息
        websocketNotity(alertDataList.get(0),alertRule,userIdList);
    }

    @Autowired
    private WebSocketServer webSocketServer;


    //websocket通知
    private void websocketNotity(AlertData alertData, AlertRule rule, Collection<Long> allUserIds) {

        //属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setAccessLocation(alertData.getRemark());
        alertNotifyVo.setFunctionName(rule.getFunctionName());
        alertNotifyVo.setAlertDataType(rule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        //向指定的人推送消息
        webSocketServer.sendMessageToConsumer(alertNotifyVo,allUserIds);

    }
}
